package com.achievo.know.job;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class BackupUtils{
	
	public static int backupMySQL(String host, String port, String user, String password, String db, String outputFile, boolean dumpMsg){
		File file = new File(outputFile);
		try{
			String[] cmd = {"mysqldump", "-f", "--host="+host, "--port="+port,
	                        "--user="+user, "--password="+password, db,
							"-r", file.getPath()};
			Process run = Runtime.getRuntime().exec(cmd);			
			
			printMsg(run.getInputStream(), "LOG", dumpMsg);
			printMsg(run.getErrorStream(), "ERROR", dumpMsg);
			int exitVal = run.waitFor();
			if(dumpMsg){				
				System.out.println("Process exitValue: " + exitVal);
			}
			return exitVal;
		}catch (Throwable t){
			t.printStackTrace();
			return -100;
		}finally{

		}
	}
	
	public static int restoreMySQL(String host, String port, String user, String password, String db, String inputFile, boolean dumpMsg){
		try{
			int BUFFER_SIZE = 1048576; // 1MB
			int read;
			String[] cmd = {"mysql", "-f", "--host="+host, "--port="+port,
	                        "--user="+user, "--password="+password, db};
			
			Process run = Runtime.getRuntime().exec(cmd);
			OutputStream writer = run.getOutputStream();
			InputStream input = new FileInputStream(inputFile);
			
			//Use char as string type will exceed the limit
			byte[] c = new byte[BUFFER_SIZE];		
			while((read = input.read(c, 0, BUFFER_SIZE - 1)) > 0){
				writer.write(c, 0, read);
				if(read < BUFFER_SIZE - 1) break;
			}

			input.close();
			writer.close();
			printMsg(run.getInputStream(), "LOG", dumpMsg);	
			printMsg(run.getErrorStream(), "ERROR", dumpMsg);
			int exitVal =run.waitFor();
			
			if(dumpMsg){				
				System.out.println("Process exitValue: " + exitVal);
			}
			return exitVal;
		}catch (Throwable t){
			t.printStackTrace();
			return -100;
		}finally{
		}
	}
	
	public static void printMsg(InputStream is, String type, boolean dumpMsg) throws Exception
	{		
		InputStreamReader isr = new InputStreamReader(is);		
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		if(dumpMsg) System.out.println("<Start of " + type + " Info>");
		while ( (line = br.readLine()) != null)
			if(dumpMsg) System.out.println(line);
		if(dumpMsg) System.out.println("<End of " + type + " Info>");
	}
}